import {Component} from '@angular/core';
import {App, IonicPage, NavController} from 'ionic-angular';
import {PublicService} from "../../common/public.service";
import {
  DELETE_FILL_VOLUME_URL, FILL_VOLUME_END_URL, FILL_VOLUME_LIST_URL, PRODUCT_LIST_URL,
  SERIES_LIST_URL
} from "../../providers/Constants";
import {HttpService} from "../../providers/HttpService";
import $ from 'jquery';

/**
 *
 * 在上班打卡后，下班打卡前，班长可以维护员工产量数据
 *
 */

@IonicPage()
@Component({
  selector: 'page-work-yield',
  templateUrl: 'work-yield.html',
})
export class WorkYieldPage {

  bzDate: string;//班组日期
  bzSelect: string;//班组选择
  workInTime: string;//上班时间
  workOutTime: string;//下班时间

  //处理类型
  public handleTypes: Array<Object> = JSON.parse(localStorage.getItem("mpower-handleTypes"));
  public attendanceTypes: Array<Object> = JSON.parse(localStorage.getItem("mpower-attendanceTypes"));

  //扫描后把数据保存在这里
  public dataList: Array<Object> = [];

  //待提交数据
  public subDataList: Array<Object> = [];

  //当前是否有修改状态行
  hasUpdating: boolean = false;
  //被修改人
  personId: string = "";
  //被编辑行
  rowid: string = "";

  //用户名
  personName: string = localStorage.getItem("mpower-personName");

  constructor(public navCtrl: NavController,
              public pub: PublicService,
              public app: App,
              private http: HttpService) {
  }

  ionViewDidLoad() {
    this.bzDate = sessionStorage.getItem("setWorkTime");
    if (!this.bzDate) {
      this.bzDate = this.pub.getDate(new Date(), 0);
    }
    this.workInTime = sessionStorage.getItem("setWorkInTime");
    this.workOutTime = sessionStorage.getItem("setWorkOutTime");
    this.bzSelect = sessionStorage.getItem("setBzSelect");

    if (sessionStorage.getItem("datalist")) {
      this.dataList = JSON.parse(sessionStorage.getItem("datalist"));
    }
  }

  ionViewWillEnter() {
    this.initList();
  }


  /**
   * 查询列表
   */
  initList() {
    this.dataList = [];
    this.subDataList = [];
    let procedureId = sessionStorage.getItem("workProcedure");
    let procedureName = sessionStorage.getItem("workProcedureName");
    let branchFactoryId = sessionStorage.getItem("fdDeptId");
    let branchFactoryName = sessionStorage.getItem("fdDeptName");

    let params = {
      sessionId: sessionStorage.getItem("session"),
      groupId: localStorage.getItem("groupId")
    };
    this.http.get(SERVER_URL + FILL_VOLUME_LIST_URL, '&', params, false).then(res => {
      if (res.success) {
        if (res.data.fillVolumeList) {
          for (let i = 0; i < res.data.fillVolumeList.length; i++) {
            let data = res.data.fillVolumeList[i];
            var obj = {
              id: data.ID ? data.ID : "",//id
              persionId: data.FDUSERID,//员工id
              persionNum: data.FDUSERNUM,//工号
              persionName: data.FDUSERNAME,//姓名
              procedureId: procedureId,//工序id
              procedureName: procedureName,//工序名称
              branchFactoryId: branchFactoryId,//工厂id
              branchFactoryName: branchFactoryName,//工厂
              handleType: data.FDSTATIONID,//工站
              series: data.FDSERIESID,//产品系列
              seriesName: data.FDSERIESNAME,//产品系列
              productId: data.FDPRODUCTID,//产品
              proName: data.FDPRONAME,
              attendanceType: data.FDKQTYPE,//考勤类型
              workTime: data.FDWORKTIME,//工作时长
              //workTime: data.FDWORKTIME ? data.FDWORKTIME : (data.FDCOMP ? (data.FDCOMP / (1000 * 60 * 60)).toFixed(1) : data.FDWORKTIME),//工作时长
              inOutput: data.FDINOUTPUT,//产量
              isSystem: data.FDISSYSTEM,//是否系统分配产量
              teamId: data.FDTEAMID,//班组id
              cardStart: data.FDCARDSTART,//上班打卡时间
              cardEnd: data.FDCARDEND,//下班打卡时间
              comp: data.FDCOMP,
              isSource: 0//是否是源（非增行项）0：是，1：否
            };
            this.dataList.push(obj);
          }
        }
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }

  /**
   * 复制行
   * @param persionId
   * @param userCode
   */
  copyRow(persionId, userCode, index) {
    if (this.hasUpdating) {
      this.pub.presentLoadingToast("请先保存编辑的数据");
      return;
    }
    let table_body = document.getElementById("table_body");
    let count = 0;
    for (let i = 0; i < table_body.children.length; i++) {
      if (table_body.children[i].id.indexOf(userCode) > -1) {
        count++;
      }
    }
    let procedureId = sessionStorage.getItem("workProcedure");
    let procedureName = sessionStorage.getItem("workProcedureName");
    let branchFactoryName = sessionStorage.getItem("fdDeptName");
    //首先获取当前行已经被增行次数，设置id为 id+_n
    let newRowId = userCode + "_" + count;
    if (this.dataList.length > 0) {
      for (let i = 0; i < this.dataList.length; i++) {
        if (this.dataList[i]['persionNum'] == userCode) {
          //同时保持到dataList中
          this.dataList.splice(index + 1, 0, {
            id: newRowId,
            branchFactoryName: branchFactoryName,
            procedureId: procedureId,//工序id
            procedureName: procedureName,
            persionId: persionId,//员工id
            persionNum: userCode,
            cardStart: this.dataList[i]['cardStart'],
            cardEnd: this.dataList[i]['cardEnd'],//下班打卡时间
            persionName: this.dataList[i]['persionName'],
            handleType: null,
            product: null,
            series: null,//产品系列
            attendanceType: null,//考勤类型
            workTime: null,//工作时长
            inOutput: null,//产量
            isSource: 1//是否是源（非增行项）0：是，1：否
          });
          break;
        }
      }
    }
  }


  /**
   * 删除行
   * @param id
   * @param personCode
   * @param personid
   * @param isSource
   */
  delRow(id: string, personid: string, isSource: string) {
    this.pub.presentCustomConfirm("确定删除改行吗？", "取消", "确定").then(() => {
      if (isSource == '1') {//增行项（未提交）
        for (let i = 0; i < this.dataList.length; i++) {
          if (this.dataList[i]['id'] == id && this.dataList[i]['persionId'] == personid) {
            this.dataList.splice(i, 1);
            break;
          }
        }
        for (let i = 0; i < this.subDataList.length; i++) {
          if (this.subDataList[i]['id'] == id && this.subDataList[i]['fdUserId'] == personid) {
            this.subDataList.splice(i, 1);
            break;
          }
        }
      } else {
        if (id) {//如果存在，则需要提交到服务器清除数据，否则本地清除数据
          let params = {
            sessionId: sessionStorage.getItem("session"),
            groupId: localStorage.getItem("groupId"),
            id: id
          };
          this.http.get(SERVER_URL + DELETE_FILL_VOLUME_URL, '&', params, false).then(res => {
            if (res.success) {
              this.initList();//重新加载列表
              this.pub.presentLoadingToast("删除成功");
            } else {
              this.pub.presentLoadingToast(res.msg);
              this.initList();//重新加载列表
              if (res.timeout) {
                setTimeout(() => {
                  this.app.getRootNav().setRoot('LoginPage');
                }, 1500);
              }
            }
          });
        }
      }
      this.hasUpdating = false;
      this.personId = "";
      this.rowid = "";
    }).catch(() => {
    });
  }


  productSeries: Array<Object> = [];

  /**
   * 选择工站，动态改变产品系列
   * 级联关系
   */
  public handleTypeChange(seriesId: string) {
    let handleType = document.getElementById("handleType")["value"];
    let params = {
      sessionId: sessionStorage.getItem("session"),
      stationCode: handleType
    };
    this.http.get(SERVER_URL + SERIES_LIST_URL, '&', params, false).then(res => {
      if (res.success) {
        this.productSeries = res.data.seriesList;
        let select = document.getElementById("productSeries");
        if (select && select['options']) {
          select['options'].length = 0;
          select['options'].add(new Option("请选择", ""));
          for (let i = 0; i < this.productSeries.length; i++) {
            if (this.productSeries[i]['CODE'] == seriesId) {
              select['options'].add(new Option(this.productSeries[i]['NAME'], this.productSeries[i]['CODE'], true, true));
            } else {
              select['options'].add(new Option(this.productSeries[i]['NAME'], this.productSeries[i]['CODE']));
            }
          }
        }
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }

  productLists: Array<Object> = [];

  /**
   * 产品列表
   */
  productSeriesChange(productSeriesId: string, productId: string) {
    if (productSeriesId == "") {
      productSeriesId = document.getElementById("productSeries")["value"];
    }
    let params = {
      sessionId: sessionStorage.getItem("session"),
      seriesCode: productSeriesId
    };
    this.http.get(SERVER_URL + PRODUCT_LIST_URL, '&', params, false).then(res => {
      if (res.success) {
        this.productLists = res.data.productList;
        let select = document.getElementById("product");
        if (select && select['options']) {
          select['options'].length = 0;
          select['options'].add(new Option("请选择", ""));
          for (let i = 0; i < this.productLists.length; i++) {
            if (this.productLists[i]['PRODUCT_CODE'] == productId) {
              select['options'].add(new Option(this.productLists[i]['PRODUCT_NAME'], this.productLists[i]['PRODUCT_CODE'], true, true));
            } else {
              select['options'].add(new Option(this.productLists[i]['PRODUCT_NAME'], this.productLists[i]['PRODUCT_CODE']));
            }
          }
        }
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }


  /**
   * 编辑当前数据
   * @param item
   */
  updateRow(item: Object) {
    let id = item['id'];
    let persionId = item['persionId'];
    //let isSource = item['isSource'];
    let attendanceType = item['attendanceType'];
    let handleType = item['handleType'];
    let series = item['series'];
    let productId = item['productId'];
    if (this.hasUpdating) {
      this.pub.presentLoadingToast("同时只能编辑一条记录");
      return;
    }
    this.hasUpdating = true;
    this.personId = persionId;
    this.rowid = id;
    //考勤
    let att = `<select id="attendanceType" >
        <option value="">请选择</option>`;
    for (let i = 0; i < this.attendanceTypes.length; i++) {
      if (this.attendanceTypes[i]['code'] == attendanceType) {
        att += `<option value="` + this.attendanceTypes[i]['code'] + `" selected>` + this.attendanceTypes[i]['name'] + ` </option>`;
      } else {
        att += `<option value="` + this.attendanceTypes[i]['code'] + `">` + this.attendanceTypes[i]['name'] + ` </option>`;
      }
    }
    att += `</select>`;

    //工站
    let Handle = `<select id="handleType" >
       <option value="">请选择</option>`;
    for (let i = 0; i < this.handleTypes.length; i++) {
      if (this.handleTypes[i]['code'] == handleType) {
        Handle += `<option value="` + this.handleTypes[i]['code'] + `" selected>` + this.handleTypes[i]['name'] + ` </option>`;
      } else {
        Handle += `<option value="` + this.handleTypes[i]['code'] + `">` + this.handleTypes[i]['name'] + ` </option>`;
      }
    }
    Handle += `</select>`;

    //产品系列
    let Series = `<select id="productSeries" ><option value="">请选择</option>`;
    for (let i = 0; i < this.productSeries.length; i++) {
      if (this.productSeries[i]['CODE'] == series) {
        Series += `<option value="` + this.productSeries[i]['CODE'] + `" selected>` + this.productSeries[i]['NAME'] + ` </option>`;
      } else {
        Series += `<option value="` + this.productSeries[i]['CODE'] + `">` + this.productSeries[i]['NAME'] + ` </option>`;
      }
    }
    Series += `</select>`;

    //产品
    let Pro = `<select id="product"><option value="">请选择</option>`;
    for (let i = 0; i < this.productLists.length; i++) {
      if (this.productLists[i]['PRODUCT_CODE'] == productId) {
        Pro += `<option value="` + this.productLists[i]['PRODUCT_CODE'] + `" selected>` + this.productLists[i]['PRODUCT_NAME'] + ` </option>`;
      } else {
        Pro += `<option value="` + this.productLists[i]['PRODUCT_CODE'] + `">` + this.productLists[i]['PRODUCT_NAME'] + ` </option>`;
      }
    }
    Pro += `</select>`;

    let Time = `<input value="` + item['workTime'] + `" type="number" min="0" max="11" step="0.1" class="input" id="workTime">`;
    let Yield = `<input value="` + item['inOutput'] + `" type="number" min="0" class="input" id="inOutput">`;

    if (id) {
      let rows = document.getElementById(id).children;
      if (rows) {
        for (let i = 0; i < rows.length; i++) {
          if (rows[i]["id"] == persionId + "Att") {
            rows[i].innerHTML = att;
          }
          if (rows[i]["id"] == persionId + "Handle") {
            rows[i].innerHTML = Handle;
          }
          if (rows[i]["id"] == persionId + "Series") {
            rows[i].innerHTML = Series;
          }
          if (rows[i]["id"] == persionId + "Pro") {
            rows[i].innerHTML = Pro;
          }
          if (rows[i]["id"] == persionId + "Time") {
            rows[i].innerHTML = Time;
          }
          if (rows[i]["id"] == persionId + "Yield") {
            rows[i].innerHTML = Yield;
          }
        }
      }
    } else {
      document.getElementById(persionId + "Att").innerHTML = att;
      document.getElementById(persionId + "Handle").innerHTML = Handle;
      document.getElementById(persionId + "Series").innerHTML = Series;
      document.getElementById(persionId + "Pro").innerHTML = Pro;
      document.getElementById(persionId + "Time").innerHTML = Time;
      document.getElementById(persionId + "Yield").innerHTML = Yield;
    }

    this.handleTypeChange(series);
    this.productSeriesChange(series, productId);

    $("#handleType").on("change", () => {
      this.handleTypeChange(series);
    });

    $("#productSeries").on("change", () => {
      this.productSeriesChange("", productId);
    });
  }


  /**
   * 单行保存
   * @param item
   */
  async saveRow(item: Object) {
    let id = item['id'];
    let persionId = item['persionId'];
    let isSource = item['isSource'];
    this.subDataList = [];
    let fdStationId = document.getElementById("handleType")["value"];
    let fdKqType = document.getElementById("attendanceType")["value"];
    let fdSeriesId = document.getElementById("productSeries")["value"];
    let fdProductId = document.getElementById("product")["value"];
    let workTime = document.getElementById("workTime")["value"];
    let inOutput = document.getElementById("inOutput")["value"];

    //判断当前工站计件方式 *计件方式：personal 个人计件，group 集体计件*/
    //集体计件产品系列是非必填项
    //集体计件则个人产量无效，不需要录入
    let jobType = "personal";
    for (let i = 0; i < this.handleTypes.length; i++) {
      if (this.handleTypes[i]["code"] == fdStationId) {
        jobType = this.handleTypes[i]["jobType"];
      }
    }

    //默认是设置的默认值
    if (!fdKqType) {
      this.pub.presentLoadingToast("考勤类型是必填项");
      return;
    }
    if (!fdStationId) {
      this.pub.presentLoadingToast("工站是必填项");
      return;
    }
    if (!fdSeriesId && jobType == 'personal') {
      this.pub.presentLoadingToast("产品系列是必填项");
      return;
    }
    if (workTime) {
      if (workTime > 11) {
        this.pub.presentLoadingToast("工作时长不能超过11个小时");
        return;
      }
      if (workTime < 0) {
        this.pub.presentLoadingToast("工作时长不能是负数");
        return;
      }
    }

    if (inOutput) {
      if (jobType == 'group') {
        this.pub.presentLoadingToastTime("集体计件不保存个人产量！", 1500);
        this.pub.sleep(1500);
      }
      if (inOutput < 0) {
        this.pub.presentLoadingToast("产量不能是负数");
        return;
      }
    }
    this.subDataList.push({
      id: id,
      fdUserId: persionId,
      fdStationId: fdStationId,
      fdKqType: fdKqType,
      fdSeriesId: fdSeriesId,
      fdProductId: fdProductId,
      fdWorkTime: workTime,
      fdInOutput: inOutput,
      isSource: isSource//是否是源（非增行项）0：是，1：否
    });
    this.submitVolume();
  }


  /**
   * 提交产量数据
   * 获取页面上所有表单数据
   */
  submitVolume() {
    let sb_subDataList = this.subDataList;
    if (sb_subDataList.length > 0) {//清除增行的id值
      for (let i = 0; i < sb_subDataList.length; i++) {
        if (sb_subDataList[i]["isSource"] == 1) {
          sb_subDataList[i]["id"] = "";
        }
      }
    }
    let params = {
      sessionId: sessionStorage.getItem("session"),
      groupId: localStorage.getItem("groupId"),
      jsonList: JSON.stringify(sb_subDataList)
    };
    this.http.post(SERVER_URL + FILL_VOLUME_END_URL, '&', params, false).then(res => {
      if (res.success) {
        this.pub.presentLoadingToast("提交成功");
        this.hasUpdating = false;
        this.personId = "";
        this.rowid = "";
        this.initList();
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }
}
